#!/bin/bash

# 查看证书详细信息的脚本
# 支持查看 nginx/ssl 下的 smartinput 证书

set -e

echo "=== 查看证书详细信息 ==="

# 默认证书文件路径
CERT_FILE="nginx/ssl/smartinput.crt"

# 检查命令行参数
if [ $# -eq 1 ]; then
    CERT_FILE="$1"
fi

# 检查证书文件是否存在
if [ ! -f "$CERT_FILE" ]; then
    echo "❌ 错误: 找不到证书文件 $CERT_FILE"
    echo ""
    echo "用法:"
    echo "  $0                    # 查看默认证书 (nginx/ssl/smartinput.crt)"
    echo "  $0 <证书文件路径>      # 查看指定证书文件"
    echo ""
    echo "示例:"
    echo "  $0"
    echo "  $0 nginx/ssl/smartinput.crt"
    echo "  $0 /path/to/your/certificate.crt"
    exit 1
fi

echo "✅ 找到证书文件: $CERT_FILE"
echo ""

# 显示证书基本信息
echo "=== 证书基本信息 ==="
echo "证书文件: $CERT_FILE"
echo "文件大小: $(ls -lh "$CERT_FILE" | awk '{print $5}')"
echo "修改时间: $(ls -l "$CERT_FILE" | awk '{print $6, $7, $8}')"
echo ""

# 显示证书主题信息
echo "=== 证书主题信息 ==="
openssl x509 -in "$CERT_FILE" -noout -subject
echo ""

# 显示证书颁发者信息
echo "=== 证书颁发者信息 ==="
openssl x509 -in "$CERT_FILE" -noout -issuer
echo ""

# 显示证书有效期
echo "=== 证书有效期 ==="
echo "生效时间: $(openssl x509 -in "$CERT_FILE" -noout -startdate | cut -d= -f2)"
echo "过期时间: $(openssl x509 -in "$CERT_FILE" -noout -enddate | cut -d= -f2)"
echo ""

# 检查证书是否过期
echo "=== 证书状态检查 ==="
if openssl x509 -in "$CERT_FILE" -checkend 0 -noout; then
    echo "✅ 证书有效（未过期）"
else
    echo "❌ 证书已过期"
fi
echo ""

# 显示证书序列号
echo "=== 证书序列号 ==="
openssl x509 -in "$CERT_FILE" -noout -serial
echo ""

# 显示签名算法
echo "=== 签名算法 ==="
openssl x509 -in "$CERT_FILE" -text -noout | grep "Signature Algorithm"
echo ""

# 显示公钥信息
echo "=== 公钥信息 ==="
openssl x509 -in "$CERT_FILE" -noout -pubkey | head -5
echo "..."
echo ""

# 显示 Subject Alternative Name (SAN) 扩展
echo "=== Subject Alternative Name (SAN) 扩展 ==="
SAN_INFO=$(openssl x509 -in "$CERT_FILE" -text -noout | grep -A 10 "Subject Alternative Name")
if [ -n "$SAN_INFO" ]; then
    echo "$SAN_INFO"
else
    echo "⚠️  未找到 SAN 扩展信息"
fi
echo ""

# 显示所有扩展信息
echo "=== 所有扩展信息 ==="
openssl x509 -in "$CERT_FILE" -text -noout | grep -A 20 "X509v3 extensions"
echo ""

# 显示证书指纹
echo "=== 证书指纹 ==="
echo "SHA1 指纹:"
openssl x509 -in "$CERT_FILE" -noout -fingerprint -sha1
echo ""
echo "SHA256 指纹:"
openssl x509 -in "$CERT_FILE" -noout -fingerprint -sha256
echo ""

# 显示证书的文本格式（完整信息）
echo "=== 完整证书信息 ==="
echo "按 Enter 键查看完整证书信息，或按 Ctrl+C 退出..."
read -r

openssl x509 -in "$CERT_FILE" -text -noout

echo ""
echo "=== 证书查看完成 ==="
echo "证书文件: $CERT_FILE"
echo "查看时间: $(date)" 